package com.qipay.admin.login;

import com.qipay.baas.model.User;
import com.qipay.core.utils.SpringContextUtil;
import com.qipay.ips.service.IpsService;
import com.qipay.ips.service.impl.IpsServiceImpl;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by dong on 2015/11/16.
 * 看登陆是否失效
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            //response.sendRedirect("/gologin");
            request.getRequestDispatcher("/login").forward(request, response);
            return false;
        }
        if (user.getLevel() == 1000) {
            return true;
        }

        //没有单名单,跳到查询白名单页面
        IpsService ipsService= (IpsService)  SpringContextUtil.getBean(IpsServiceImpl.class);
        if(ipsService.isNotWhiteIp(user.getName())){
            request.getRequestDispatcher("/ips/query").forward(request, response);
            return false;
        }
        if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
            AuthPassport authPassport = ((HandlerMethod) handler).getMethodAnnotation(AuthPassport.class);
            //没有声明需要权限,或者声明不验证权限
            if (authPassport != null) {
                String key = authPassport.key();
                if (key.endsWith("admin")) {
                    if (user.getLevel() < 500) {
                        request.getRequestDispatcher("/err/403").forward(request, response);
                        return false;
                    }
                }
                if (key.endsWith("agent")) {
                    if (user.getLevel() < 200) {
                        request.getRequestDispatcher("/err/403").forward(request, response);
                        return false;
                    }
                }
            }
        }
        return true;
    }
}
